package com.osce.ex.service.tools;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.csce.domain.entity.exam.ExQuestion;
import com.doudou.core.container.ArrUtil;
import com.doudou.core.thread.ExecutorUtil;
import com.osce.common.constant.CacheConstants;
import com.osce.common.core.redis.RedisCache;
import com.osce.ex.mapper.ExQuestionMapper;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @author zzxjs
 * @since 2023/8/8
 * 题目缓存服务类
 */
@Service
public class ExQuestionCacheService {
    private static final Log log = LogFactory.get(ExQuestionCacheService.class);

    @Resource
    RedisCache cache;
    @Resource
    ExQuestionMapper baseMapper;

    /**
     * 缓存题目
     */
    @PostConstruct
    public void cacheQuestion() {
        ExecutorUtil.asyncExecute(() -> {
            log.info("starting cache questions.....");
            delQuestion();
            cacheQuestion(baseMapper.selectAll());
            log.info("cache questions success");
        });
    }

    /**
     * 缓存单个题目
     */
    public void cacheQuestion(ExQuestion exQuestion) {
        cache.setCacheMapValue(CacheConstants.EX_QUESTION_MAP_KEY, CacheConstants.questionKey(exQuestion.getId()), exQuestion);
    }

    /**
     * 获取单个题目
     */
    public ExQuestion getCacheQuestion(Long id) {
        return cache.getCacheMapValue(CacheConstants.EX_QUESTION_MAP_KEY, CacheConstants.questionKey(id));
    }

    /**
     * 缓存多个个题目
     */
    public void cacheQuestion(List<ExQuestion> exQuestions) {
        cache.setCacheMap(CacheConstants.EX_QUESTION_MAP_KEY, new HashMap<String, ExQuestion>() {{
            for (ExQuestion question : exQuestions) {
                put(CacheConstants.questionKey(question.getId()), question);
            }
        }});
    }

    public void cacheQuestion(ExQuestion... exQuestions) {
        cacheQuestion(ArrUtil.toList(exQuestions));
    }

    /**
     * 删除一个或多个题目
     */
    public void delQuestion(Long... ids) {
        cache.deleteCacheMapValue(CacheConstants.EX_QUESTION_MAP_KEY, Arrays.stream(ids).map(CacheConstants::questionKey).toArray(String[]::new));
    }

    /**
     * 删除所有题目
     */
    public void delQuestion() {
        cache.deleteObject(CacheConstants.EX_QUESTION_MAP_KEY);
    }
}
